<?php

namespace App\Http\Controllers\V1\API;

use App\Http\Controllers\V1\API\BaseController;
use App\Models\V1\ApplyPays;
use App\Models\V1\DailyUse;
use App\Models\V1\NewStudent;
use App\Models\V1\Pays;
use App\Models\V1\ReceiveStatus;
use App\Models\V1\ReportProcess;
use App\Models\V1\ResultMajors;
use App\Models\V1\Textbook;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Validator;
use Log;

class ReportProcessController extends BaseController
{
    /***
     * 获取流程数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getProcesses(Request $request)
    {
        $code = $request->get('userID');

        // 自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
            'data' => array()
        );
        $error = $this->validateApply($request, $result);
        if (!empty($error) || isset($error)) {
            $result = $error;
            return $this->sendResponse($result, $result['errorCode']);
        }
        $processes = $this->getProcessList($code);
        if ($processes->isEmpty()) {
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = Response::$statusTexts[Response::HTTP_NO_CONTENT];
        } else {
            // 格式化数据
            $resultProcess = array();
            for ($i = 0; $i < count($processes); $i++) {
                $item = $processes[$i];
                $formatProcess['processCode'] = $item['code'];
                $formatProcess['processName'] = $item['name'];
                switch ($i) {
                    //身份确认
                    case 0:
                        $status = $this->getIsReceive($code, 1);
                        $formatProcess['status'] = $status;
                        break;
                    //缴费
                    case 1:
                        $status = $this->getIsPay($code);
                        $formatProcess['status'] = $status;
                        break;
                    //领取物品
                    case 2:
                        $status = $this->getIsReceive($code, 2);
                        $formatProcess['status'] = $status;
                        break;
                    //领取教材
                    case 3:
                        $status = $this->getIsReceive($code, 3);
                        $formatProcess['status'] = $status;
                        break;
                    //领取钥匙
                    case 4:
                        $status = $this->getIsReceive($code, 5);
                        $formatProcess['status'] = $status;
                        break;
                }
                array_push($resultProcess, $formatProcess);
            }
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = Response::$statusTexts[Response::HTTP_OK];
            $result['data'] = $resultProcess;
        }
        return $this->sendResponse($result, $result['errorCode']);
    }

    /***
     * 获取流程详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getProcessDetail(Request $request)
    {
        $code = $request->get('userID');
        $process_code = $request->get('processCode');

        // 自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
            'data' => array()
        );
        $error = $this->validateApply($request, $result);
        if (!empty($error) || isset($error)) {
            $result = $error;
            return $this->sendResponse($result, $result['errorCode']);
        }

        $process = $this->getProcessByCode($code, $process_code);
        if (empty($process) || !isset($process)) {
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = Response::$statusTexts[Response::HTTP_NO_CONTENT];
        } else {

            // 格式化数据
            $formatProcess = array();
            $formatProcess['processCode'] = $process['code'];
            $formatProcess['processName'] = $process['name'];
            $formatProcess['detailTime'] = isset($process['detail']) ? $process['detail'] : '';
            $formatProcess['address'] = isset($process['address']) ? $process['address'] : '';
            $formatProcess['receptionist'] = isset($process['reception_person']) ? $process['reception_person'] : '';
            $formatProcess['formalities'] = isset($process['handle_procedures']) ? $process['handle_procedures'] : '';
            $formatProcess['remark'] = isset($process['remark']) ? $process['remark'] : '';
            $relate_information = $process['relate_information'];
            if (empty($relate_information)) {
                $formatProcess['relate'] = array();
            } else {
                $relate = $this->formatRelate($relate_information, $code);
                $formatProcess['relate'] = $relate;
            }
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = Response::$statusTexts[Response::HTTP_OK];
            $result['data'] = $formatProcess;
        }
        return $this->sendResponse($result, $result['errorCode']);
    }


    private function formatProcess($code, $process_code)
    {
        $result = array();
        $process = $this->getProcessByCode($code, $process_code);
        if (empty($process) || !isset($process)) {
            $result = array();
        } else {
            // 格式化数据
            $formatProcess = array();
            $formatProcess['processCode'] = $process['code'];
            $formatProcess['processName'] = $process['name'];
            $formatProcess['detailTime'] = isset($process['detail']) ? $process['detail'] : '';
            $formatProcess['address'] = isset($process['address']) ? $process['address'] : '';
            $formatProcess['receptionist'] = isset($process['reception_person']) ? $process['reception_person'] : '';
            $formatProcess['formalities'] = isset($process['handle_procedures']) ? $process['handle_procedures'] : '';
            $formatProcess['remark'] = isset($process['remark']) ? $process['remark'] : '';
            $relate_information = $process['relate_information'];
            if (empty($relate_information)) {
                $formatProcess['relate'] = array();
            } else {
                $relate = $this->formatRelate($relate_information, $code);
                $formatProcess['relate'] = $relate;
            }
            return $formatProcess;
        }
    }


    //获取所有的流程详情
    public function getAllProcessDetail(Request $request)
    {
        $code = $request->get('userID');
        // 自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
            'data' => array()
        );
        $error = $this->validateApply($request, $result);
        if (!empty($error) || isset($error)) {
            $result = $error;
            return $this->sendResponse($result, $result['errorCode']);
        }
        $processList = $this->getProcessList($code);
        Log::info('$processList', ['$processList' => $processList]);
        if ($processList->isEmpty()) {
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = Response::$statusTexts[Response::HTTP_NO_CONTENT];
        } else {
            // 格式化数据
            $resultProcess = array();
            for ($i = 0; $i < count($processList); $i++) {
                $item = $processList[$i];
                $formatProcess = $this->formatProcess($code, $item['code']);
                switch ($i) {
                    //身份确认
                    case 0:
                        $status = $this->getIsReceive($code, 1);
                        $formatProcess['status'] = $status;
                        break;
                    //缴费
                    case 1:
                        $status = $this->getIsPay($code);
                        $formatProcess['status'] = $status;
                        break;
                    //领取物品
                    case 2:
                        $status = $this->getIsReceive($code, 2);
                        $formatProcess['status'] = $status;
                        break;
                    //领取教材
                    case 3:
                        $status = $this->getIsReceive($code, 3);
                        $formatProcess['status'] = $status;
                        break;
                    //领取钥匙
                    case 4:
                        $status = $this->getIsReceive($code, 5);
                        $formatProcess['status'] = $status;
                        break;
                }
                array_push($resultProcess, $formatProcess);
            }
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = Response::$statusTexts[Response::HTTP_OK];
            $result['data'] = $resultProcess;
        }
        return $this->sendResponse($result, $result['errorCode']);
    }

    /***
     * 用户报到(扫描二维码)
     * @param Request $request
     */
    public function userReport(Request $request)
    {
        $code = $request->get('userID');

        //1:报到(身份确认) 2.生活用品发放 3.教材发放 4.校服发放 5.宿舍钥匙发放  6.现场缴费
        $type = $request->get('type');

        // 自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
        );
        $error = $this->validateApply($request, $result);
        if (!empty($error) || isset($error)) {
            $result = $error;
            return $this->sendResponse($result, $result['errorCode']);
        }
        //检测用户是否已报到
        $data = ReceiveStatus::where(['exam_code' => $code, 'type' => $type])->first();
        //有记录，
        if (!empty($data) || isset($data)) {
            $status = $data['status'];
            if ($status) {
                //表示用户已扫过二维码，并且老师已确认
                $result['errorCode'] = Response::HTTP_OK;
                switch ($type) {
                    case 1:
                        $result['errorMsg'] = '用户已完成身份确认';
                        break;
                    case 2:
                        $result['errorMsg'] = '用户已领取物品';
                        break;
                    case 3:
                        $result['errorMsg'] = '用户已领取教材';
                        break;
                    case 4:
                        $result['errorMsg'] = '用户已领取校服';
                        break;
                    case 5:
                        $result['errorMsg'] = '用户已领取钥匙';
                        break;
                    case 6:
                        $result['errorMsg'] = '用户已完成支付';
                        break;
                    default:
                        $result['errorMsg'] = '用户已完成操作';
                }
            } else {
                //表示用户已扫过二维码，但老师未确认
                $result['errorCode'] = Response::HTTP_OK;
                $result['errorMsg'] = '请等待教师确认';
            }
        } else {
            //无记录
            //如果是缴费，判断是否已通过微信／支付宝缴纳
            if ($type == 6) {
                $is_pay = $this->getIsPay($code);
                if ($is_pay) {
                    $result['errorCode'] = Response::HTTP_OK;
                    $result['errorMsg'] = '您已通过线上缴费';
                    return $this->sendResponse($result, $result['errorCode']);
                }
            }
            $insertData = [
                'exam_code' => $code,
                'type' => $type,
                'status' => false
            ];
            $resp = ReceiveStatus::create($insertData);
            if ($resp) {
                $result['errorCode'] = Response::HTTP_OK;
                $result['errorMsg'] = '扫描成功，请等待教师确认';
            } else {
                $result['errorCode'] = Response::HTTP_OK;
                $result['errorMsg'] = '扫描失败，请重试';
            }
        }
        return $this->sendResponse($result, $result['errorCode']);
    }


    /***
     * 验证用户报到获取流程接口
     * @param Request $request
     */
    private function validateApply(Request $request)
    {
        //校验规则
        $rules = array();
        $rules['userID'] = 'required|exists:basic_new_students,exam_code,deleted_at,NULL|bail';

        //错误提示信息
        $messages = array();
        $messages['userID.required'] = '用户代码不能为空';
        $messages['userID.exists'] = '用户不存在';

        $validator = Validator::make($request->all(), $rules, $messages);  //第一个参数是提交的数据，第二个是校对规则，第三个是错误信息
        $errors = $validator->errors()->all(); //这是捕获到的所有参数验证的错误信息
        if (!empty($errors)) {
            $first_errors = $errors[0];
            $result['errorCode'] = Response::HTTP_BAD_REQUEST;
            $result['errorMsg'] = $first_errors;
            return $result;
        }
    }

    /***
     * 获取流程列表
     * @param $code
     * @return mixed
     */
    private function getProcessList($code)
    {
        $arrival_code = $this->getArrivalCode($code);
        $data = ReportProcess::where('arrival_code', $arrival_code)->get();
        return $data;
    }

    /***
     * 获取流程列表
     * @param $code
     * @return mixed
     */
    private function getProcessByCode($code, $process_code)
    {
        $arrival_code = $this->getArrivalCode($code);
        $data = ReportProcess::where(['arrival_code' => $arrival_code, 'code' => $process_code])->first();
        return $data;
    }

    /***
     * 1:报到(身份确认) 2.生活用品发放 3.教材发放 4.校服发放 5.宿舍钥匙发放
     * 获取物品领取状态
     * @param $code
     * @return string
     */
    private function getIsReceive($code, $type)
    {
        $is_register = ReceiveStatus::where(['exam_code' => $code, 'type' => $type, 'status' => true])
            ->first();
        if (!empty($is_register) || isset($is_register)) {
            return true;
        }
        return false;
    }


    /***
     * 检测是否缴费
     * @param $code
     * @return mixed
     */
    private function getIsPay($code)
    {
        $pay = ApplyPays::where(['exam_code' => $code, 'status' => true])->first();
        if (!empty($pay) || isset($pay)) {
            return true;
        }
        return false;
    }


    /***
     * 获取当前的迎新代码
     * @return array
     */
    private function getArrivalCode($code)
    {
        $student = $this->getStudentInfo($code);
        return $student['arrival_code'];
    }

    /***
     * 根据考试号获取学生基础信息
     * @param $code
     */
    private function getStudentInfo($code)
    {
        $student = NewStudent::where('exam_code', $code)->first();
        return $student;
    }

    /***
     * 获取学生代码录取专业
     * @param $code
     */
    private function getStudentMajor($code)
    {
        $major = ResultMajors::where('exam_code', $code)->first();
        return $major;
    }


    /***
     * $type
     * 格式化相关信息
     * @param $relate_information
     */
    private function formatRelate($relate_information, $code)
    {
        if (empty($relate_information)) {
            return array();
        } else {
            $content = json_decode($relate_information, true);
            $relate_code = $content['code'];

            $data = array();
            if ($relate_code === 'relate1') {
                //费用清单
                $data = $this->getPayList($code);

            } elseif ($relate_code === 'relate2') {
                //物品清单
                $data = $this->getDailyUseList($code);

            } elseif ($relate_code === 'relate3') {
                //教材清单
                $data = $this->getTextbookList($code);
            }
            return $data;
        }
    }

    /***
     * 根据费用列表
     * @param $code
     */
    private function getPayList($code)
    {
        $arrival_code = $this->getArrivalCode($code);
        $payList = Pays::where('arrival_code', $arrival_code)->orderBy('id', 'asc')->get();
        if ($payList->isEmpty()) {
            return array();
        } else {
            // 格式化数据
            $pays = array();
            foreach ($payList as $item) {
                $formatPay = array();
                $formatPay['name'] = $item['name'];
                $formatPay['content'] = $item['amount'] . $item['unit'];
                array_push($pays, $formatPay);
            }
            return $pays;
        }
    }

    /***
     * 根据物品列表
     * @param $code
     */
    private function getDailyUseList($code)
    {
        $arrival_code = $this->getArrivalCode($code);
        $payList = DailyUse::where('arrival_code', $arrival_code)->orderBy('id', 'asc')->get();
        if ($payList->isEmpty()) {
            return array();
        } else {
            // 格式化数据
            $pays = array();
            foreach ($payList as $item) {
                $formatPay = array();
                $formatPay['name'] = $item['name'];
                $formatPay['content'] = $item['count'] . $item['unit'];
                array_push($pays, $formatPay);
            }
            return $pays;
        }
    }

    /***
     * 根据教材列表
     * @param $code
     */
    private function getTextbookList($code)
    {
        $arrival_code = $this->getArrivalCode($code);
        $payList = Textbook::where('arrival_code', $arrival_code)->orderBy('id', 'asc')->get();
        if ($payList->isEmpty()) {
            return array();
        } else {
            // 格式化数据
            $pays = array();
            foreach ($payList as $item) {
                $formatPay = array();
                //根据学生的录取专业获取教材数据
                $enroll_major = $this->getStudentMajor($code);
                //教材的领用专业
                $majors = json_decode($item['majors'], true);
                if (!empty($majors)) {
                    if (in_array($enroll_major['code'], $majors)) {
                        $formatPay['name'] = $item['name'];
                        $formatPay['content'] = $item['count'] . $item['unit'];
                        array_push($pays, $formatPay);
                    }
                }
            }
            return $pays;
        }
    }

}
